'use strict';
const db = uniCloud.database();  // 确保数据库对象正确初始化

/**
 * 云函数：提交答案
 * @param {Object} event - 请求参数
 * @param {string} event.user_id - 用户ID
 * @param {Array} event.answers - 答案列表
 * @returns {Object} - 提交结果
 */
exports.main = async (event, context) => {
  const { user_id, answers } = event;
  try {
    const userCollection = db.collection('users');  // 确保用户集合初始化
    const wrongQuestionCollection = db.collection('wrong_questions');  // 确保错题集合初始化
    const answerHistoryCollection = db.collection('answer_history');  // 确保答题记录集合初始化

    // 获取用户信息
    const userRes = await userCollection.doc(user_id).get();
    if (!userRes.data || !userRes.data.length) {
      return { code: -1, msg: '用户不存在' };
    }
    const user = userRes.data[0];

    let correctCount = 0;
    const wrongQuestions = [];
    const answerHistoryData = [];  // 存储所有答题记录

    // 遍历用户答案，进行比对
    for (const answer of answers) {
      const questionRes = await db.collection('questions').doc(answer.question_id).get(); // 获取题目信息
      const question = questionRes.data[0];
      
      if (!question) {
        continue;  // 如果题目不存在，跳过
      }

      const correct_answer = question.answer;  // 获取正确答案

      const answerRecord = {
        user_id,
        question_id: answer.question_id,
        answer: answer.user_answer,
        correct_answer,
        correct: answer.user_answer === correct_answer,
        answered_at: new Date(),
        explanation: question.explanation || ''
      };

      // 将每个答题记录添加到answerHistoryData
      answerHistoryData.push(answerRecord);

      // 错题处理
      if (answerRecord.correct === false) {
        wrongQuestions.push({
          user_id,
          question_id: answer.question_id,
          content: question.content,
          options: question.options,
          user_answer: answer.user_answer,
          correct_answer,
          explanation: question.explanation,
          created_at: new Date()  // 保存为ISO时间戳
        });
      }

      // 统计正确题数
      if (answerRecord.correct) {
        correctCount++;
      }
    }

    // 批量插入答题记录到answer_history表
    if (answerHistoryData.length > 0) {
      await answerHistoryCollection.add(answerHistoryData);
    }

    // 如果有错题，插入到错题本
    if (wrongQuestions.length > 0) {
      await wrongQuestionCollection.add(wrongQuestions);
    }

    // 计算得分
    const pointsEarned = correctCount * 2;
    const newPoints = (user.points || 0) + pointsEarned;

    // 更新用户积分
    await userCollection.doc(user_id).update({
      points: newPoints,
      updated_at: new Date()  // 更新用户更新时间
    });

    return {
      code: 0,
      data: {
        points: pointsEarned,
        totalPoints: newPoints,
        correctCount,
        wrongCount: wrongQuestions.length,
        wrong_questions: wrongQuestions  // 返回错题数据
      },
      msg: '提交成功'
    };
  } catch (e) {
    console.error('提交答案失败:', e);
    return { code: -1, msg: '提交答案失败，网络错误' };  // 捕获并返回更详细的错误信息
  }
};